
// import React, { useEffect, useState } from 'react';
// import axios from 'axios';
// import {
//   BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, ResponsiveContainer, LabelList, Legend
// } from 'recharts';

// const AnalyticsTable = () => {
//   const [data, setData] = useState([]);
//   const [loading, setLoading] = useState(true);
//   const [isFallback, setIsFallback] = useState(false);

//   useEffect(() => {
//     const fetchData = async () => {
//       try {
//         const response = await axios.get('http://localhost:5000/api/analsyTable');
//         setData(response.data.data);
//         setIsFallback(response.data.isFallback || false);
//       } catch (error) {
//         console.error('获取数据失败:', error);
//       } finally {
//         setLoading(false);
//       }
//     };

//     fetchData();
//   }, []);

//   if (loading) return <div className="text-center text-gray-600">加载中...</div>;

//   const maxPeople = Math.max(...data.map(d => d['参加人数'])) || 10;

//   return (
//     <div className="p-8 max-w-5xl mx-auto bg-white rounded-2xl shadow-md">
//   <div className="flex justify-center mb-4">
//     <h2 className="text-3xl font-bold text-gray-800">
//       📊 活动类型参与人数统计
//     </h2>
//   </div>

//   {isFallback && (
//     <p className="text-sm text-yellow-600 mb-4 text-center">
//       ⚠️ 当前显示的是模拟数据
//     </p>
//   )}

//       <ResponsiveContainer width="100%" height={450}>
//         <BarChart
//           data={data}
//           layout="vertical"
//           margin={{ top: 20, right: 30, left: 80, bottom: 20 }}
//         >
//           {/* 背景网格 */}
//           <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />

//           {/* X轴 */}
//           <XAxis
//             type="number"
//             domain={[0, maxPeople + 5]}
//             ticks={Array.from({ length: maxPeople + 1 }, (_, i) => i)}
//             tick={{ fontSize: 14, fill: '#6b7280' }}
//             axisLine={{ stroke: '#d1d5db' }}
//           />

//           {/* Y轴 */}
//           <YAxis
//             dataKey="活动类型"
//             type="category"
//             tick={{ fontSize: 14, fill: '#374151' }}
//             axisLine={false}
//           />

//           {/* Tooltip */}
//           <Tooltip
//             contentStyle={{ backgroundColor: '#ffffff', border: '1px solid #e5e7eb', borderRadius: '8px' }}
//             cursor={{ fill: '#f3f4f6' }}
//           />

//           {/* 渐变定义 */}
//           <defs>
//             <linearGradient id="barGradient" x1="0" y1="0" x2="1" y2="0">
//               <stop offset="0%" stopColor="#6366f1" />
//               <stop offset="100%" stopColor="#818cf8" />
//             </linearGradient>
//           </defs>

//           {/* 柱状条 */}
//           <Bar dataKey="参加人数" fill="url(#barGradient)" barSize={40} radius={[10, 10, 10, 10]}>
//             <LabelList dataKey="参加人数" position="right" style={{ fill: '#111827', fontWeight: 'bold' }} />
//           </Bar>

//           {/* 图例（可选） */}
//           <Legend />
//         </BarChart>
//       </ResponsiveContainer>
//     </div>
//   );
// };

// export default AnalyticsTable;



import React, { useEffect, useState } from 'react';
import axios from 'axios';
import {
  BarChart, Bar, XAxis, YAxis, Tooltip, CartesianGrid, ResponsiveContainer, LabelList, Legend
} from 'recharts';

const AnalyticsTable = () => {
  // 活动类型数据
  const [activityData, setActivityData] = useState([]);
  const [loadingActivity, setLoadingActivity] = useState(true);
  const [isFallbackActivity, setIsFallbackActivity] = useState(false);

  // 社团统计数据
  const [clubData, setClubData] = useState([]);
  const [loadingClub, setLoadingClub] = useState(true);
  const [isFallbackClub, setIsFallbackClub] = useState(false);

  // 获取活动类型统计数据
  useEffect(() => {
    const fetchActivityData = async () => {
      try {
        const res = await axios.get('http://localhost:5000/api/analsyTable');
        setActivityData(res.data.data);
        setIsFallbackActivity(res.data.isFallback || false);
      } catch (error) {
        console.error('获取活动类型数据失败:', error);
      } finally {
        setLoadingActivity(false);
      }
    };

    fetchActivityData();
  }, []);

  // 获取社团统计数据
  useEffect(() => {
    const fetchClubData = async () => {
      try {
        const res = await axios.get('http://localhost:5000/api/clubStats');
        setClubData(res.data.data);
        setIsFallbackClub(res.data.isFallback || false);
      } catch (error) {
        console.error('获取社团统计数据失败:', error);
      } finally {
        setLoadingClub(false);
      }
    };

    fetchClubData();
  }, []);

  if (loadingActivity || loadingClub) return <div className="text-center text-gray-600">加载中...</div>;

  const maxPeopleActivity = Math.max(...activityData.map(d => d['参加人数'])) || 10;
  const maxPeopleClub = Math.max(
    ...clubData.map(d => Math.max(d['活动数量'], d['总参与人数']))
  ) || 10;

  return (
    <div className="p-8 max-w-6xl mx-auto bg-white rounded-2xl shadow-md space-y-16">
      {/* 活动类型统计图 */}
      <div>
        <div className="flex justify-center mb-4">
          <h2 className="text-3xl font-bold text-gray-800">📊 活动类型参与人数统计</h2>
        </div>
        {isFallbackActivity && (
          <p className="text-sm text-yellow-600 mb-4 text-center">
            ⚠️ 当前显示的是模拟数据
          </p>
        )}
        <ResponsiveContainer width="100%" height={450}>
          <BarChart
            data={activityData}
            layout="vertical"
            margin={{ top: 20, right: 30, left: 80, bottom: 20 }}
          >
            <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
            <XAxis
              type="number"
              domain={[0, maxPeopleActivity + 5]}
              ticks={Array.from({ length: maxPeopleActivity + 1 }, (_, i) => i)}
              tick={{ fontSize: 14, fill: '#6b7280' }}
              axisLine={{ stroke: '#d1d5db' }}
            />
            <YAxis
              dataKey="活动类型"
              type="category"
              tick={{ fontSize: 14, fill: '#374151' }}
              axisLine={false}
            />
            <Tooltip
              contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px' }}
              cursor={{ fill: '#f3f4f6' }}
            />
            <defs>
              <linearGradient id="barGradient" x1="0" y1="0" x2="1" y2="0">
                <stop offset="0%" stopColor="#6366f1" />
                <stop offset="100%" stopColor="#818cf8" />
              </linearGradient>
            </defs>
            <Bar dataKey="参加人数" fill="url(#barGradient)" barSize={40} radius={[10, 10, 10, 10]}>
              <LabelList dataKey="参加人数" position="right" style={{ fill: '#111827', fontWeight: 'bold' }} />
            </Bar>
            <Legend />
          </BarChart>
        </ResponsiveContainer>
      </div>

      {/* 社团统计图 */}
      <div>
        <div className="flex justify-center mb-4">
          <h2 className="text-3xl font-bold text-gray-800">🏫 社团活动统计图</h2>
        </div>
        {isFallbackClub && (
          <p className="text-sm text-yellow-600 mb-4 text-center">
            ⚠️ 当前显示的是模拟数据
          </p>
        )}
        <ResponsiveContainer width="100%" height={450}>
          <BarChart
            data={clubData}
            layout="vertical"
            margin={{ top: 20, right: 30, left: 100, bottom: 20 }}
          >
            <CartesianGrid strokeDasharray="3 3" stroke="#e5e7eb" />
            <XAxis
              type="number"
              domain={[0, maxPeopleClub + 10]}
              tick={{ fontSize: 14, fill: '#6b7280' }}
              axisLine={{ stroke: '#d1d5db' }}
            />
            <YAxis
              dataKey="社团名称"
              type="category"
              tick={{ fontSize: 14, fill: '#374151' }}
              axisLine={false}
            />
            <Tooltip
              contentStyle={{ backgroundColor: '#fff', border: '1px solid #e5e7eb', borderRadius: '8px' }}
              cursor={{ fill: '#f3f4f6' }}
            />
            <Legend />
            <Bar dataKey="活动数量" fill="#60a5fa" barSize={20} radius={[10, 10, 10, 10]} />
            <Bar dataKey="总参与人数" fill="#34d399" barSize={20} radius={[10, 10, 10, 10]} />
          </BarChart>
        </ResponsiveContainer>
      </div>
    </div>
  );
};

export default AnalyticsTable;
